package com.ujoku.controller;

import com.easemob.server.httpclient.service.EasemobIMUsersService;
import com.labillusion.core.platform.crypto.MD5;
import com.labillusion.core.platform.exception.ResourceNotFoundException;
import com.labillusion.core.platform.web.pagination.PaginationForm;
import com.labillusion.core.platform.web.rest.RESTController;
import com.labillusion.core.platform.web.rest.exception.InvalidRequestException;
import com.labillusion.core.util.MessageSourceUtils;
import com.labillusion.core.util.StringUtils;
import com.ujoku.context.ActionContext;
import com.ujoku.context.constants.ContextConstants;
import com.ujoku.context.constants.MessageConstants;
import com.ujoku.domain.*;
import com.ujoku.domain.admin.Parameter;
import com.ujoku.interceptor.LoginRequired;
import com.ujoku.request.*;
import com.ujoku.service.*;
import com.ujoku.service.admin.ParametersService;
import com.ujoku.view.builder.CartBuilder;
import com.ujoku.view.domain.EasemobView;
import com.ujoku.view.domain.FriendView;
import com.ujoku.view.domain.MemberSearchView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.net.URL;
import java.util.*;


/**
 * Created by Greg on 2014/10/20.
 */
@RestController
public class MemberController extends RESTController {

    private static Logger logger = LoggerFactory.getLogger(MemberController.class);

    @Autowired
    public MemberService service;

    @Autowired
    public SMSService SMSService;
    @Autowired
    protected MessageSourceUtils messageSourceUtils;

    @Autowired
    protected ActionContext actionContext;

    @Autowired
    private CartService cartService;

    @Autowired
    private CartBuilder cartBuilder;

    @Autowired
    private ParametersService parametersService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private PasswordChangeLogService passwordChangeLogService;

    @Autowired
    private EasemobIMUsersService easemobIMUsersService;

    @Autowired
    private OrderItemService orderItemService;

    @Value("#{configProperties['settings.customer.upload']}")
    private String uploadPath;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Member Login(@Valid @RequestBody LoginForm form) throws Exception {

        Member member = (Member) service.selectByUserName(form.getUserName());

        if (member == null || !MD5.encrypt(form.getPassword()).equals(member.getPassword()))
            throw new InvalidRequestException("The User name or password did not match our records.");

        if(!member.isIMUser()){
            easemobIMUsersService.IMUserSyncCreate(form.getUserName());
            member.setIMUser(true);
            service.update(member);
        }

        if(StringUtils.hasText(form.getiOSDeviceToken())){
            member.setiOSDeviceToken(form.getiOSDeviceToken());
            service.update(member);
        }

        return getMemberForLogin(member);
    }

    @RequestMapping(value = "/member/session", method = RequestMethod.GET)
    @ResponseBody
    public Member getMemberInfoFromSession(ModelMap map, HttpSession session) {

        Member member = actionContext.getMember();

        return member;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public String Logout(HttpSession session) throws Exception {

        if (session != null)
            session.invalidate();


        return "Successfully";
    }

    @RequestMapping(value = "/member/create", method = RequestMethod.POST)
    @ResponseBody
    public Member Create(@Valid @RequestBody MemberCreateForm form, HttpSession session) throws Exception {

        CheckCaptcha(form, session);

        Member member = (Member) service.selectByUserName(form.getUserName());

        if (member != null)
            throw new InvalidRequestException("registered", messageSourceUtils.getMessage("member.has.registered"));

        member = new Member();
        member.setUser_name(form.getUserName());

        member.setPassword(MD5.encrypt(form.getPassword()));

        member.setPhone_mob(form.getUserName());

        member.setPortrait(false);

        service.setLevelName(member);

        // IM注册
        easemobIMUsersService.IMUserAsyncCreate(form.getUserName());

        service.insert(member);

        session.setAttribute("Member", member);
        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());

        //清空验证码
        session.setAttribute("Captcha", null);
        return member;
    }

    @RequestMapping(value = "/thirdPartyLogin", method = RequestMethod.POST)
    @ResponseBody
    public Member WeChatLogin(@Valid @RequestBody WeChatLoginForm form){

        Member member = (Member) service.selectByWxId(form.getWxId(),form.getType());

        if(member == null)
            throw new ResourceNotFoundException("member no found");

        if(!member.isIMUser()){
            easemobIMUsersService.IMUserSyncCreate(member.getUser_name());
            member.setIMUser(true);
            service.update(member);
        }

        if(StringUtils.hasText(form.getiOSDeviceToken())){
            member.setiOSDeviceToken(form.getiOSDeviceToken());
            service.update(member);
        }

        return getMemberForLogin(member);
    }

    @RequestMapping(value = "/thirdPartyLoginBinding", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public Member WeChatLoginBinding(@Valid @RequestBody WeChatLoginForm form){

        Member member = actionContext.getMember();

        if(member == null || form.getMemberId() != member.getUser_id())
            throw new ResourceNotFoundException("member no found");

        if("WEB".equals(form.getType())) {
            member.setWebWxId(form.getWxId());
        }else if("APP".equals(form.getType())){
            member.setAppWxId(form.getWxId());
        }else{
            throw new InvalidRequestException("no wxId type");
        }
        service.update(member);

        return getMemberForLogin(member);
    }

    @RequestMapping(value = "/thirdPartyBinding", method = RequestMethod.POST)
    @ResponseBody
    public Member WeChatBinding(@Valid @RequestBody WeChatBindingForm form, HttpSession session,HttpServletRequest request) throws Exception {
        if(form.getWxId() == null)
            throw new ResourceNotFoundException("no wxId");
        CheckCaptcha(form, session);

        Member member = (Member) service.selectByUserName(form.getUserName());

        if (member == null){
            member = new Member();
            member.setUser_name(form.getUserName());

            member.setPassword(MD5.encrypt(form.getPassword()));

            member.setPhone_mob(form.getUserName());

            member.setPortrait(false);

            if("WEB".equals(form.getType())) {
                member.setWebWxId(form.getWxId());
            }else if("APP".equals(form.getType())){
                member.setAppWxId(form.getWxId());
                member.setNickname(form.getNickName());
                if(form.getHeadImgUrl() != null) {
                    member.setPortrait(true);
                    member.setUpdateTime(new Date());
                }
            }else{
                throw new InvalidRequestException("no wxId type");
            }

            service.setLevelName(member);

            // IM注册
            easemobIMUsersService.IMUserAsyncCreate(form.getUserName());

            service.insert(member);

            session.setAttribute("Member", member);
            Visitor visitor = actionContext.getCurrentVisitor();
            visitor.setUser_id(member.getUser_id());

            if(form.getHeadImgUrl() != null)
                getImgFormUrl(form.getHeadImgUrl(),member.getUser_id(),request);

            //清空验证码
            session.setAttribute("Captcha", null);

            member = (Member) service.selectByUserName(form.getUserName());

            return getMemberForLogin(member);

        }else if (member != null && !MD5.encrypt(form.getPassword()).equals(member.getPassword()))
            throw new InvalidRequestException("password","The password did not match our records.");
        else{
            if("WEB".equals(form.getType())) {
                member.setWebWxId(form.getWxId());
            }else if("APP".equals(form.getType())){
                member.setAppWxId(form.getWxId());
                member.setNickname(form.getNickName());

                if(form.getHeadImgUrl() != null) {
                    getImgFormUrl(form.getHeadImgUrl(), member.getUser_id(), request);
                    member.setPortrait(true);
                    member.setUpdateTime(new Date());
                }
            }else{
                throw new InvalidRequestException("no wxId type");
            }
            service.update(member);

            //清空验证码
            session.setAttribute("Captcha", null);

            member = (Member) service.selectByUserName(form.getUserName());

            return getMemberForLogin(member);
        }
    }

    private Member getMemberForLogin(Member member){
        List<Address> addresses = addressService.selectByMemberId(member.getUser_id());
        if(addresses.size() > 0){
            member.setPrimaryAddress(addresses.stream().filter(a->a.getPrimary()).findFirst().orElse(null));
        }

        Map<String,Object> query = new HashMap<>();
        query.put("memberId",member.getUser_id());

        int count = orderItemService.selectSalesCount(query);

        member.setSalesCount(count);

        actionContext.setMember(member);

        cartBuilder.updateRelateInfo(member);

        return member;
    }

    private void CheckCaptcha(MemberCreateForm form, HttpSession session) {
        Calendar expiredTime = (Calendar) session.getAttribute("CaptchaExpiredTime");
        String captcha = (String) session.getAttribute("Captcha");
        //如果验证码时间过期, throw exception
        if (!form.getCaptcha().equals(captcha) || Calendar.getInstance().after(expiredTime))
            throw new InvalidRequestException("captcha", "验证码错误");
    }

    private void CheckCaptcha(MemberPayPasswordForm form, HttpSession session) {
        Calendar expiredTime = (Calendar) session.getAttribute("CaptchaExpiredTime");
        String captcha = (String) session.getAttribute("Captcha");
        //如果验证码时间过期, throw exception
        if (!form.getCaptcha().equals(captcha) || Calendar.getInstance().after(expiredTime))
            throw new InvalidRequestException("captcha", "验证码错误");
    }

    private void CheckCaptcha(MemberSecurityCodeForm form, HttpSession session) {
        Calendar expiredTime = (Calendar) session.getAttribute("CaptchaExpiredTime");
        String captcha = (String) session.getAttribute("Captcha");
        //如果验证码时间过期, throw exception
        if (!form.getCaptcha().equals(captcha) || Calendar.getInstance().after(expiredTime))
            throw new InvalidRequestException("captcha", "验证码错误");
    }

    @RequestMapping(value = "/member/sendSMS", method = RequestMethod.POST)
    @ResponseBody
    public String sendSMS(HttpServletRequest request, @Valid @RequestBody SendSMSForm form, HttpSession session) throws IOException {
        Member member = (Member) service.selectByUserName(form.getPhone());

        if (member != null && form.getType() == 0)
            throw new InvalidRequestException("phone", "手机号已经被注册!");

        if (member == null && form.getType() == 1)
            throw new InvalidRequestException("phone", "该用户不存在!");

        Calendar expiredTime = (Calendar) session.getAttribute("CaptchaExpiredTime");
        if (Calendar.getInstance().before(expiredTime)) {
            throw new InvalidRequestException("phone", "不能重复发送短信!");
        }

        String captcha = SMSService.CalculateCaptcha();
        session.setAttribute("Captcha", captcha);

        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, 1);
        session.setAttribute("CaptchaExpiredTime", now);

        SMSService.toYiChi(form.getPhone(), captcha);

        return "Successfully";
    }

    @RequestMapping(value = "/member/updateInfo", method = RequestMethod.PUT)
    @LoginRequired
    @ResponseBody
    public Member updateInfo(@Valid @RequestBody MemberUpdateForm form, HttpServletRequest request, HttpSession session) throws Exception {

        Member member = actionContext.getMember();

        member.setNickname(form.getNickname());
        if(StringUtils.hasText(form.getEmail()))
            member.setEmail(form.getEmail());
        else
            member.setEmail("");
        service.update(member);
        member.setUser_name(form.getNickname());

        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());

        actionContext.setMember(member);
        return member;
    }

    @RequestMapping(value = "/member/portrait", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public Member setPortrait(@RequestParam MultipartFile[] file,ModelMap map, HttpSession session, HttpServletRequest request) throws IOException {

        Member member = actionContext.getMember();

        String dir = request.getRealPath(uploadPath);
        File folder = new File(dir);
        if(!folder.exists()){
            folder.mkdirs();
        }

        String headPath = dir + "/" + member.getUser_id() + "_head.jpg";
        File portrait = new File(headPath);
        file[0].transferTo(portrait);


        if (!member.isPortrait())
            member.setPortrait(true);

        member.setUpdateTime(new Date());
        service.update(member);

        actionContext.setMember(member);

        return member;
    }

    @RequestMapping(value = "/member/update", method = RequestMethod.PUT)
    @ResponseBody
    @LoginRequired
    public String update(@Valid @RequestBody MemberCreateForm form, HttpServletRequest request, HttpSession session) throws Exception {

        CheckCaptcha(form, session);

        Member member = actionContext.getMember();

        if (member == null)
            throw new InvalidRequestException("unFound", messageSourceUtils.getMessage("member.not.found"));

        if(!checkChangeCount(member.getUser_id(),1)){
            throw new InvalidRequestException("password","设置密码已经超过每日限制次数");
        }

        member.setPassword(MD5.encrypt(form.getPassword()));
        service.update(member);

        actionContext.setMember(member);

        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());

        session.setAttribute("Captcha", null);
        session.setAttribute("CaptchaExpiredTime", null);
        return "Successfully";
    }

    @RequestMapping(value = "/member/updatePayPassword", method = RequestMethod.PUT)
    @ResponseBody
    @LoginRequired
    public Member updatePayPassword(@Valid @RequestBody MemberPayPasswordForm form, HttpServletRequest request, HttpSession session) throws Exception {

        CheckCaptcha(form, session);

        Member member = actionContext.getMember();

        if (member == null)
            throw new InvalidRequestException("unFound", messageSourceUtils.getMessage("member.not.found"));

        member.setPay_password(MD5.encrypt(form.getPay_password()));
        if(member.getPassword().equals(member.getPay_password()))
            throw new InvalidRequestException("password", "支付密码不能与登录密码相同");

        if(!checkChangeCount(member.getUser_id(),2)){
            throw new InvalidRequestException("payPassword","设置密码已经超过每日限制次数");
        }

        member.setDefault_pay_password(true);
        service.update(member);


        actionContext.setMember(member);

        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());

        session.setAttribute("Captcha", null);
        session.setAttribute("CaptchaExpiredTime", null);
        return member;
    }

    @RequestMapping(value = "/member/updateSecurityCode", method = RequestMethod.PUT)
    @ResponseBody
    @LoginRequired
    public String updateSecurityCode(@Valid @RequestBody MemberSecurityCodeForm form, HttpServletRequest request, HttpSession session) throws Exception {

        CheckCaptcha(form, session);

        Member member = actionContext.getMember();

        if (member == null)
            throw new InvalidRequestException("unFound", messageSourceUtils.getMessage("member.not.found"));

        member.setSecurity_code(MD5.encrypt(form.getSecurity_code()));

        member.setDefault_security_code(true);
        service.update(member);

        actionContext.setMember(member);

        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());

        session.setAttribute("Captcha", null);
        session.setAttribute("CaptchaExpiredTime", null);
        return "Successfully";
    }

    private boolean checkChangeCount(int memberId,int type){
        Map<String,Object> query = new HashMap<>();
        query.put("memberId",memberId);
        query.put("type",type);

        int count = passwordChangeLogService.selectCount(query);
        if (count >= 2) {
            return false;
        } else {
            PasswordChangeLog passwordChangeLog = new PasswordChangeLog();
            passwordChangeLog.setMemberId(String.valueOf(memberId));
            passwordChangeLog.setType(type);
            passwordChangeLogService.insert(passwordChangeLog);
            return true;
        }

    }

    @RequestMapping(value = "/member/checkPayPassword", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String checkPayPassword(@Valid @RequestBody CheckPayPasswordForm form, HttpServletRequest request, HttpSession session) throws Exception {

        Member member = actionContext.getMember();
        if (!member.isDefault_pay_password())
            throw new InvalidRequestException("payPassword", "支付密码未设置");

        if (!MD5.encrypt(form.getPay_password()).equals(member.getPay_password()))
            throw new InvalidRequestException("payPassword", "支付密码不正确");

        return "Successfully";
    }

    @RequestMapping(value = "/member/checkSecurityCode", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String checkSecurityCode(@Valid @RequestBody CheckSecurityCodeForm form, HttpServletRequest request, HttpSession session) throws Exception {

        Member member = actionContext.getMember();
        if (!member.isDefault_security_code())
            throw new InvalidRequestException("securityCode", "安全码未设置");

        if (!MD5.encrypt(form.getSecurity_code()).equals(member.getSecurity_code()))
            throw new InvalidRequestException("securityCode", "安全码不正确");

        return "Successfully";
    }

    @RequestMapping(value = "/member/forget", method = RequestMethod.PUT)
    @ResponseBody
    public String forgetPassword(@Valid @RequestBody MemberCreateForm form, HttpSession session){
        CheckCaptcha(form, session);

        Member member = (Member)service.selectByUserName(form.getUserName());

        if (member == null)
            throw new InvalidRequestException("unFound", messageSourceUtils.getMessage("member.not.found"));

        if(!checkChangeCount(member.getUser_id(),1)){
            throw new InvalidRequestException("password","设置密码已经超过每日限制次数");
        }

        member.setPassword(MD5.encrypt(form.getPassword()));
        service.update(member);


        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());

        session.setAttribute("Captcha", null);
        session.setAttribute("CaptchaExpiredTime", null);
        return "Successfully";
    }

    @RequestMapping(value = "/member/search", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public MemberSearchView search(@Valid @RequestBody MemberSearchForm form, HttpServletRequest request) {
        Member member = actionContext.getMember();

        Map<String, Object> query = form.getQueryMap();
        if(StringUtils.hasText(form.getQ()))
            query.put("q", form.getQ());
        query.put("selfId", member.getUser_id());

        if(form.getNumberList() != null && form.getNumberList().size() > 0)
        {
            query.put("numberList", form.getNumberList());
        }

        int count = service.selectCount(query);
        if (count == 0)
            throw new ResourceNotFoundException("can not found member");

        List<Member> members = service.selectList(query);

        Map<String, Object> myFriendQuery = new HashMap<>();
        myFriendQuery.put("memberId", member.getUser_id());
        List<Member> myFriendList = service.getMyFriendList(myFriendQuery);

        List<FriendView> friendViewList = new ArrayList<>();

        members.forEach(m -> {

            FriendView friendView = new FriendView();

            service.setMemberPortrait(m,request);
            friendView.setFriend(myFriendList.stream().anyMatch(i -> i.getUser_id() == m.getUser_id()));
            BeanUtils.copyProperties(m, friendView);

            Parameter p = parametersService.getParameterByKey(ContextConstants.MEMBER_LEVEL + m.getLevel());
            if (p != null) {
                friendView.setLevelName(p.getMark());
            }

            friendViewList.add(friendView);

        });

        MemberSearchView memberSearchView = new MemberSearchView();
        memberSearchView.setCount(count);
        memberSearchView.setList(friendViewList);

        return memberSearchView;
    }


    @RequestMapping(value = "/friend/{id}", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String addFriedApply(@PathVariable Integer id) {
        Member member = actionContext.getMember();

        Member friend = checkFriendForm(id, member);

        Map<String, Object> myFriendQuery = new HashMap<>();
        myFriendQuery.put("memberId", member.getUser_id());
        List<Member> myFriendList = service.getMyFriendList(myFriendQuery);
        //判断是否已经存在
        if (myFriendList.stream().anyMatch(i -> i.getUser_id() == id))
            throw new InvalidRequestException("friend","该用户已经是您的好友");

        Message message = messageService.bulid(MessageConstants.FRIEND_APPLY, friend.getUser_id(), new String[]{member.getUser_name()});
        message.setFromMemberId(member.getUser_id());
        messageService.insert(message);

        return "success";
    }

    @RequestMapping(value = "/friendAccept/{id}", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String addFried(@PathVariable Integer id){
        Member member = actionContext.getMember();

        Member friend = checkFriendForm(id, member);

        if(service.isFriendShip(member.getUser_id(), id) == 0){
            service.addFriend(member.getUser_id(), id);
            member.setFriendCount(service.getMyFriendCount(member.getUser_id()));
            service.update(member);
        }

        if(service.isFriendShip(id, member.getUser_id()) == 0) {
            service.addFriend(id, member.getUser_id());
            friend.setFriendCount(service.getMyFriendCount(friend.getUser_id()));
            service.update(friend);
        }

        easemobIMUsersService.IMUserAddFriend(member.getPhone_mob(),friend.getPhone_mob());

        actionContext.setMember(member);

        Message message = messageService.bulid(MessageConstants.FRIEND_ACCEPT, friend.getUser_id(), new String[]{member.getUser_name()});
        messageService.insert(message);

        updateMessageStatus(friend.getUser_id(),member.getUser_id(),MessageConstants.FRIEND_APPLY);
        updateMessageStatus(member.getUser_id(),friend.getUser_id(),MessageConstants.FRIEND_APPLY);

        return "success";
    }

    private Member checkFriendForm(Integer id, Member member) {
        if (member.getUser_id() == id)
            throw new InvalidRequestException("memberId invalid");

        Member friend = (Member) service.selectById(id);
        if (friend == null)
            throw new ResourceNotFoundException("can not found this member");

        return friend;
    }

    private void updateMessageStatus(Integer fromMemberId,Integer toMemberId,String type){
        Map<String,Object> query = new HashMap<>();
        query.put("fromMemberId",fromMemberId);
        query.put("toMemberId",toMemberId);
        query.put("type",type);

        messageService.updateOne(query);
    }

    @RequestMapping(value = "/friend/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    @LoginRequired
    public String removeFried(@PathVariable Integer id) {
        Member member = actionContext.getMember();

        Member friend = checkFriendForm(id, member);

        if(service.isFriendShip(member.getUser_id(), id) > 0) {
            service.removeFriend(member.getUser_id(), id);
            member.setFriendCount(service.getMyFriendCount(member.getUser_id()));
            service.update(member);
        }

        if(service.isFriendShip(id, member.getUser_id()) > 0) {
            service.removeFriend(id, member.getUser_id());
            friend.setFriendCount(service.getMyFriendCount(friend.getUser_id()));
            service.update(friend);
        }

        //IM删除好友
        easemobIMUsersService.IMUserDeleteFriend(member.getPhone_mob(),friend.getPhone_mob());

        actionContext.setMember(member);

        Message message = messageService.bulid(MessageConstants.FRIEND_CANCEL, friend.getUser_id(), new String[]{member.getUser_name()});
        messageService.insert(message);

        return "success";
    }

    @RequestMapping(value = "/friend", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public MemberSearchView myFriendList(@Valid @RequestBody PaginationForm form , HttpServletRequest request) {
        Member member = actionContext.getMember();
        Map<String, Object> myFriendQuery = form.getQueryMap();
        myFriendQuery.put("memberId", member.getUser_id());

        List<Member> memberList = service.getMyFriendList(myFriendQuery);
        if (memberList.size() == 0) {
            throw new ResourceNotFoundException("can not found friend");
        }

        List<FriendView> friendViewList = new ArrayList<>();
        memberList.forEach(m -> {
            FriendView friendView = new FriendView();
            service.setMemberPortrait(m,request);

            BeanUtils.copyProperties(m, friendView);

            Parameter p = parametersService.getParameterByKey(ContextConstants.MEMBER_LEVEL + m.getLevel());
            if (p != null) {
                friendView.setLevelName(p.getMark());
            }

            friendViewList.add(friendView);
            friendView.setFriend(true);
        });


        int count = service.getMyFriendCount(member.getUser_id());

        MemberSearchView memberSearchView = new MemberSearchView();
        memberSearchView.setList(friendViewList);
        memberSearchView.setCount(count);

        return memberSearchView;
    }

    private void getImgFormUrl(String url,int memberId,HttpServletRequest request){
        String dir = request.getRealPath(uploadPath);
        File folder = new File(dir);
        if(!folder.exists()){
            folder.mkdirs();
        }

        String headPath = dir + "/" + memberId + "_head.jpg";

        try {
            URL headUrl = new URL(url);
            InputStream in = new BufferedInputStream(headUrl.openStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n = 0;
            while (-1!=(n=in.read(buf)))
            {
                out.write(buf, 0, n);
            }
            out.close();
            in.close();
            byte[] response = out.toByteArray();

            FileOutputStream fos = new FileOutputStream(headPath);
            fos.write(response);
            fos.close();
        } catch (Exception e) {
            logger.warn(e.getMessage());
            logger.warn("URL:" + url);
        }
    }

    @RequestMapping(value = "/easemobInfo", method = RequestMethod.POST)
    @ResponseBody
    public EasemobView getView(@Valid @RequestBody EasemobForm easemobForm){
        if (!StringUtils.hasText(easemobForm.getUser_name())){
            throw new ResourceNotFoundException("用户名不能为空");
        }

        Map<String,Object> query = new HashMap<>();
        query.put("user_name",easemobForm.getUser_name());
        Member member = (Member)service.selectOne(query);

        EasemobView easemobView = new EasemobView();
        easemobView.setHeadPortraitUrl(service.getMemberPortrait(member.isPortrait(), member.getUser_id(), member.getUpdateTime()));
        easemobView.setNickname(member.getUser_name());
        easemobView.setUser_id(member.getUser_id());

        return easemobView;
    }

}

